<?php

class Admin_Table_Tags extends Apk_Db_Table
{
	protected $_name      = 'tags';
    protected $_primary   = 'id';

    protected $_ERROR = '';

    public function GetError()
    {
    	return $this->_ERROR;
    }

    public function GetDataList($page=1, $sort=null, $page_count=null, $params=null)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'name', 'add_date', 'is_active'));

    	if(count($params) > 0)
		foreach($params as $k => $v)
		{
			switch ($k)
			{
				case 'is_top':
				case 'is_active':
					if(intval($v) >= 0 && trim($v) != '')
					$sel->where($this->_name.'.'.$k.' = ?', intval($v));
					break;
				case 's':
					if(trim($v) != '')
					{
						$sel->where($this->_name.'.name like \''.$v.'%\'');
					}
					break;
				default:
					if(intval($v) > 0)
					$sel->where($this->_name.'.'.$k.' = ?', intval($v));
			}
		}

		if(!is_null($sort) && strlen($sort) > 0) $sel->order($this->_name.'.'.$sort);
		else $sel->order($this->_name.'.name asc');

    	return $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $page_count));
    }

    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('id = ?', $id);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();
    }

    public function GetTagByName($tag)
    {
		$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->where('name = ?', $tag);

		$data = $this->getList($sel)->toArray();

		if(count($data) > 0) return $data[0]['id'];
		else return 0;
    }

    public function SearchTagsByName($tag)
    {
		$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->where("name like '".$tag."%'")
					->order('name')
					->limit(10);

		$data = $this->getList($sel)->toArray();
		$ret = array();

		if(count($data) > 0)
		foreach($data as $k => $v)
		{
			$ret[$k]['key'] = $v['id'];
			$ret[$k]['value'] = $v['name'];
		}

		return $ret;
    }

    public function GetTagsByObjId($object_name = 'articles', $object_id)
    {
        $table_name = 'tags_to_'.$object_name;
        $table_field_name = 'id_'.$object_name;

    	$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->join($table_name, $table_name.'.id_tag = tags.id')
					->where($table_name.'.'.$table_field_name.' = ?', $object_id);

		return $this->getList($sel)->toArray();
    }

    public function GetTagsStringByObjId($object_name = 'articles', $object_id)
    {
		$tags = $this->GetTagsByObjId($object_name, $object_id);

		$ret = '';
		foreach ($tags as $tag)
		{
			if($ret != '') $ret .= ', ';
			$ret .= $tag['name'];
		}
		return $ret;
    }

	public function insertStr($tags_str, $object_name = 'articles', $object_id, $user_id)
    {
        $table_name = 'tags_to_'.$object_name;
        $table_field_name = 'id_'.$object_name;

    	$tags_arr = explode(',', $tags_str);

    	$this->getAdapter()->delete($table_name, $table_field_name.' = '.$object_id);

        if(count($tags_arr) > 0)
        foreach($tags_arr as $tag) {
        	$tag = trim($tag);

        	if($tag == '') continue;

        	$tag_id = $this->GetTagByName($tag);

        	if($tag_id == 0){
        		$d = array();
	        	$d['name'] = $tag;
	        	$d['add_date'] = time();
	        	$d['modify_date'] = time();
	        	$d['add_user_id'] = $user_id;
	        	$d['modify_user_id'] = $user_id;

	        	try{
	        		$tag_id = parent::insert($d);
	        	}catch (Exception $e){
	        		//echo 'hello'; die();
	        	}
        	}

        	if($tag_id > 0)
        	{
        	   $d = array(
        	      'id_tag' => $tag_id,
        	      $table_field_name => $object_id
        	   );

        	   try{
        	   		$this->getAdapter()->insert($table_name, $d);
	        	}catch (Exception $e){
	        		//echo 'hello'; die();
	        	}
        	}

        }
    }

    public function insertTags($tags, $object_name = 'articles', $object_id, $user_id)
    {
    	$table_name = 'tags_to_'.$object_name;
        $table_field_name = 'id_'.$object_name;

    	$this->getAdapter()->delete($table_name, $table_field_name.' = '.$object_id);

        if(count($tags) > 0)
        foreach($tags as $tag_id) {

        		if(!(intval($tag_id) > 0  && strlen(intval($tag_id)) == strlen($tag_id)))
        		{
            		$d = array();
    	        	$d['name'] = $tag_id;
    	        	$d['add_date'] = time();
    	        	$d['modify_date'] = time();
    	        	$d['add_user_id'] = $user_id;
    	        	$d['modify_user_id'] = $user_id;

    	        	try{
    	        		$tag_id = parent::insert($d);
    	        	}catch (Exception $e){
    	        		//echo 'hello'; die();
    	        	}
        		}


        	   $d = array(
        	      'id_tag' => $tag_id,
        	      $table_field_name => $object_id
        	   );

        	   try{
        	   		$this->getAdapter()->insert($table_name, $d);
	        	}catch (Exception $e){
	        		echo $e->__toString();
	        		die();
	        	}
        }
    }

    public function update(array $data, $id)
    {
		try{
    		parent::update($data, 'id = '.$id);
		}catch(Exception $e)
		{
			echo $e->__toString();
			die();
		}
		return true;
    }

    public function remove($items)
    {
    	foreach($items as $k => $id)
    	{
	    	$this->getAdapter()->delete('tags_to_articles', 'id_tag = '.$id);
	    	parent::delete('id = '.$id);
    	}
	}


    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
        	case 'add_date':
            case 'public_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>